<template>
  <a-modal width="700px" v-model:visible="visible" :title="title" @before-ok="onOk">
    <a-form ref="formRef" :model="form" size="medium" auto-label-width>
      <a-form-item field="title" label="标题">
        <a-input v-model="form.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item field="versionNumber" label="版本号">
        <a-input v-model="form.versionNumber" placeholder="请输入版本号" />
      </a-form-item>
      <a-form-item field="versionName" label="版本名称">
        <a-input v-model="form.versionName" placeholder="请输入版本名称" />
      </a-form-item>
      <a-form-item field="userVersionNumber" label="会员中心版本号">
        <a-input v-model="form.userVersionNumber" placeholder="请输入会员中心版本号" />
      </a-form-item>
      <a-form-item field="downloadLink" label="下载链接">
        <a-input v-model="form.downloadLink" placeholder="请输入下载链接" />
      </a-form-item>
      <a-form-item field="size" label="文件大小">
        <a-input v-model="form.size" placeholder="请输入文件大小" />
      </a-form-item>
      <a-form-item field="desc" label="描述">
        <a-textarea
          :auto-size="{
            minRows: 6,
            maxRows: 10
          }"
          v-model="form.desc"
        />
      </a-form-item>
      <a-form-item field="type" label="版本类型">
        <a-radio-group v-model="form.type">
          <a-radio :value="0">升级</a-radio>
          <a-radio :value="1">内测</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="form.type == 1" field="isOpenAllTest" label="是否开启全员内测">
        <a-radio-group v-model="form.isOpenAllTest">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item field="interval" label="间隔时间">
        <a-input-number :min="0" v-model="form.interval" placeholder="请输入间隔时间(分钟)" />
      </a-form-item>
      <a-form-item label="是否强制更新" v-if="form.type == 0" field="isForce">
        <a-switch :checked-value="1" :unchecked-value="0" v-model="form.isForce"></a-switch>
      </a-form-item>
      <a-form-item label="内测邀请码" field="studentIds">
        <div>
          <a-space class="mb-m">
            <a-upload
              size="mini"
              name="file"
              :show-file-list="false"
              :headers="{ Authorization: token }"
              :custom-request="getInviteCode"
            >
              <template #upload-button>
                <a-button type="primary" :loading="importLoading">
                  <template #icon>
                    <icon-upload />
                  </template>
                  上传
                </a-button>
              </template>
            </a-upload>
            <a-button type="outline" @click="clearStudentIds" class="ml-m">
              <template #icon>
                <icon-delete />
              </template>
              清空
            </a-button>
          </a-space>
          <a-input-tag placeholder="请输入邀请码" v-model="form.studentIds" @change="formatInviteCode" />
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { appVersionConfigEdit, appVersionConfigImport } from '@/apis'
import { Message, Modal } from '@arco-design/web-vue'
import { reAssign } from '@/utils/common'
import { getToken } from '@/utils/auth'

defineProps({
  cateList: Array,
  platformList: Array,
  authorList: Array
})
const emit = defineEmits(['getTableData'])

// 上传组件需要增加token
const tokenSource = getToken()
const token = tokenSource ? `'Bearer ${tokenSource}'` : ''
const title = computed(() => (form.id ? '编辑版本信息' : '新增版本信息'))
const visible = ref(false)
const formRef = ref()
const importLoading = ref(false)

const form = reactive({
  id: undefined,
  title: undefined,
  desc: undefined,
  versionNumber: undefined,
  versionName: undefined,
  userVersionNumber: undefined,
  downloadLink: undefined,
  isOpenAllTest: undefined,
  size: undefined,
  isForce: undefined,
  type: 1,
  interval: undefined,
  studentIds: []
})

// 打开编辑框并回显表单值
const addOrEdit = async (item) => {
  visible.value = true
  if (!item.studentIds) item.studentIds = []
  else if (typeof item.studentIds === 'string') item.studentIds = item.studentIds.split(',')
  reAssign(form, item)
  form.isForce = item ? item.isForce : 0
  form.type = item ? item.type : 1
  item && formRef.value?.validate()
}

// 上传邀请码
const getInviteCode = async (option) => {
  try {
    importLoading.value = true
    const { fileItem } = option
    const formData = new FormData()
    formData.append('file', fileItem.file)
    const res = await appVersionConfigImport(formData)
    const inviteCodes = res.data.map((item) => {
      return item.toString()
    })
    form.studentIds = form.studentIds.concat(inviteCodes)
    formatInviteCode()
    Message.success('导入成功')
  } finally {
    importLoading.value = false
  }
}

// 清空邀请码
const clearStudentIds = () => {
  Modal.warning({
    title: '提示',
    content: '是否确认清空？',
    hideCancel: false,
    onOk: () => {
      form.studentIds = []
    }
  })
}

// 邀请码去重
const formatInviteCode = () => {
  const set = new Set(form.studentIds)
  form.studentIds = [...set]
}

// 点击确认添加/编辑
const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  if (form.type == 1) form.isForce = 0
  await appVersionConfigEdit({ ...form, studentIds: form.studentIds.join(',') })
  Message.success('操作成功')
  emit('getTableData')
  return true
}

provide('formRef', formRef)
defineExpose({ addOrEdit })
</script>
<style scoped lang="scss">
.tab-box {
  min-height: 100px;
  max-height: 400px;
  overflow-y: auto;
}
</style>
